const api = require('../../../../ws_micro_shop/utils/api.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const order = require('../../../../ws_micro_shop/utils/orders.js');
const utils = require('../../../../ws_micro_shop/utils/utils.js');

let app = getApp();
let timer = null;
let interval = null;

Page({
  data: {
    again: true,
    hide: 1,
    qrcode: '',
    theme: app.themeData,
    showpaytypes: false,
    unit: '',
    imgUrl: app.imgUrl,
    isAdmin: false,
  },
  onLoad(opts) {
    let that = this;
    let options = opts || {};
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    let userinfo = wx.getStorageSync('user_info');
    Number(userinfo.info) === 0 && (tools.onGetInfo(this, userinfo.auth_mode));
    this.setData({
      opts: options,
      commentSwitch: wx.getStorageSync('store').comment_switch,
      isAdmin: options.admin && options.admin == 'yes' ? true : false,
    });
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    app.pageOnLoad(this);
  },
  onShow() {
    this.loadOrderDetails();
  },
  onHide() {
    timer && clearInterval(timer);
    interval && clearInterval(interval);
  },
  onUnload() {
    timer && clearInterval(timer);
    interval && clearInterval(interval);
  },
  loadOrderDetails() {
    interval && clearInterval(interval);
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.order.detail,
      data: {
        order_id: that.options.id,
      },
      success: function(res) {
        if (res.code === 0) {
          interval && clearInterval(interval);
          if (Number(res.data.status) !== 3) {
            that.countDownRun(res.data.limit_time_ms);
          }
          that.setData({
            order: res.data,
            'order.o_type': 2,
            pay_type_list: res.data.pay_type_list,
            limit_time: res.data.limit_time,
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                app.util.navigateTo('/ws_micro_shop/pages/order/order', {}, true);
              }
            },
          });
        }
      },
      complete: function() {
        wx.hideLoading();
      },
    });
    app.loadShopSetting().then(res => {
      that.setData(res);
    });
  },
  customerTo() {
    let { card_openid, card_toopenid, card_id } = this.data;
    let url = '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0';
    app.util.navigateTo(url);
  },
  copyText(e) {
    let text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function() {
        wx.showToast({
          title: '已复制',
          icon: 'none',
        });
      },
    });
  },
  countDownRun(limit_time_ms) {
    let that = this;
    interval = setInterval(function() {
      let leftTime = (new Date(limit_time_ms[0], limit_time_ms[1] - 1, limit_time_ms[2], limit_time_ms[3], limit_time_ms[4], limit_time_ms[5])) - (new Date());
      let { days, hours, minutes, seconds } = utils.getLeaveTime(leftTime / 1000);
      that.setData({
        limit_time: {
          days,
          hours,
          mins: minutes,
          secs: seconds,
        },
      });
    }, 1000);
  },
  toConfirm() {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.order.confirm,
      data: {
        order_id: that.data.order.order_id,
      },
      success: function(res) {
        if (res.code === 0) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/ws_micro_shop_pt/pages/pt/order-details/order-details?id=' + that.data.order.order_id,
                });
              }
            },
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/ws_micro_shop_pt/pages/pt/order-details/order-details?id=' + that.data.order.order_id,
                });
              }
            },
          });
        }
      },
      complete: function() {
        wx.hideLoading();
      },
    });
  },
  goToGroup() {
    wx.redirectTo({
      url: '/ws_micro_shop_pt/pages/pt/group/details?oid=' + this.data.order.order_id,
    });
  },
  showPayType(e) {
    this.setData({
      showpaytypes: true,
      orderID: e.currentTarget.dataset.id,
      orderType: e.currentTarget.dataset.type,
      discountId: e.currentTarget.dataset.discount == 1 ? e.currentTarget.dataset.payment : -1,
    });
  },
  disabledClick() {
    // it`s necessary
  },
  hidePayType() {
    this.setData({
      showpaytypes: false,
    });
  },
  orderPay(e) {
    order.orderPay(e, this.data.orderID, this.data.orderType);
    this.setData({
      showpaytypes: false,
    });
  },
  orderQrcode(e) {
    let _this = this;
    let orderId = _this.data.order.order_id;
    let orderNo = _this.data.order.order_no;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    if (_this.data.order.offline_qrcode) {
      _this.setData({
        hide: 0,
        qrcode: _this.data.order.offline_qrcode,
      });
      wx.hideLoading();
    } else {
      order.orderQrcode(orderNo, orderId,2,res => {
        if (res) {
          _this.setData({
            hide: 0,
            qrcode: res.data.url,
          });
          if (timer) {
            timer && clearInterval(timer);
          }
          _this.Loop(orderId);
        }
      });
    }
  },
  callsomeone(e) {
    let mobile = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: mobile,
    });
  },
  location() {
    let shop = this.data.order.shop;
    wx.openLocation({
      latitude: parseFloat(shop.latitude),
      longitude: parseFloat(shop.longitude),
      address: shop.address,
      name: shop.name,
    });
  },
  location2() {
    let page = this;
    let { lng, lat, address, name } = page.data.order;
    wx.openLocation({
      latitude: parseFloat(lat),
      longitude: parseFloat(lng),
      address: address,
      name: name,
    });
  },
  getOfflineQrcode(e) {
    let that = this;
    let orderId = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.order.get_qrcode,
      data: {
        order_no: e.currentTarget.dataset.no,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            hide: 0,
            qrcode: res.data.url,
          });
          if (timer) {
            timer && clearInterval(timer);
          }
          that.Loop(orderId);
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
          });
        }
      },
      complete: function() {
        wx.hideLoading();
      },
    });
  },
  hide() {
    timer && clearInterval(timer);
    this.setData({
      hide: 1,
    });
  },
  Loop(id) {
    let that = this;
    timer = setInterval(function() {
      app.ws_micro_shoprequest({
        url: api.default.orderClerk,
        data: {
          order_id: id,
          type: 'pt',
        },
        success: function(res) {
          if (res.code === 0) {
            if (Number(res.data) === 1) {
              timer && clearInterval(timer);
              that.setData({
                hide: 1,
              });
              that.loadOrderDetails();
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
      });
    }, 2000);
  },
  orderRevoke(e) {
    let { id, type, msg, order_cancel } = e.currentTarget.dataset;
    order.orderRevoke(id, msg, type, order_cancel, res => {
      if (res.confirm) {
        wx.navigateBack({
          delta: 1,
        });
      }
    });
  },
  orderConfirm(e) {
    let _this = this;
    let { id, type } = e.currentTarget.dataset;
    order.orderConfirm(id, type, res => {
      if (res.code === 0) {
        _this.loadOrderDetails();
      }
    });
  },
  deleteOrder(e) {
    order.deleteOrder(e, res => {
      if (res) {
        wx.navigateBack({
          delta: 1,
        });
      }
    });
  },
  ping(e) {
    order.ping(e);
  },
  refund(e) {
    console.log('refund', e);
    app.util.navigateTo('/ws_micro_shop/pages/order-refund/order-refund', {
      id: this.data.opts.id,
      entry: 'pt',
    });
  },
  showExpressList() {
    app.util.navigateTo('/ws_micro_shop/pages/express-detail/express-detail', {
      id: this.data.opts.id,
      type: 'pt',
    });
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
});
